import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/const/app_content.dart';
import 'package:freedom/const/game_const.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/page/mahjong/bloc/room_info.dart';
import 'package:freedom/page/mahjong/bloc/user_state.dart';
import 'package:freedom/page/mahjong/common/mahjong_context.dart';
import 'package:freedom/page/mahjong/common/message_content.dart';
import 'package:freedom/page/mahjong/mahjong_game.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/widget/current_game_commons.dart';
import 'package:freedom/widget/mahjong_common.dart';

class RecodeDialog extends StatefulWidget {
  final MahjongIndexGame game;
  const RecodeDialog({super.key, required this.game});

  @override
  State<RecodeDialog> createState() => _RecodeDialogState();
}

class MenuInfo {
  String name;
  Function fun;
  MenuInfo(this.name, this.fun);
}

class _RecodeDialogState extends State<RecodeDialog> {
  double _opacity = 1.0;
  MahjongIndexGame get game => widget.game;
  UserState? selectUser;
  List<UserState> allUser = [];
  List<Widget> userCards = [];
  double dialogWidth = ScreenUtil().screenWidth * 0.8;
  double cardHeight = ScreenUtil().screenWidth * 0.8 / 14;
  List<MenuInfo>? menuList;
  int menuIndex = 0;
  @override
  void initState() {
    menuList = [
      MenuInfo("下一局", () {
        var data = MessageContent<List<MahjongMessage>>(
            messageFromUid: 1,
            type: MessageContent.MT_ACT,
            body: [MahjongMessage(type: MessageAction.PREPARE)]).toJson();
        Http.getInstance().request<Restful>(ApiRouter.roomMessage,
            contentType: ContentType.json,
            type: RequestEnum.POST,
            showErrorMsg: true,
            data: data, success: (data) {
          game.overlays.remove(MahjongOverlay.balanceDialog);
        });
      }),
      MenuInfo("游戏结束", () {
        MahjongContext().gameOver();
        game.overlays.remove(MahjongOverlay.balanceDialog);
        MahjongContext().showGameOverWidget(MahjongContext.roomInfo);
      }),
      MenuInfo("关闭窗口", () {
        game.overlays.remove(MahjongOverlay.balanceDialog);
      }),
    ];
    allUser = MahjongContext.roomInfo.gameInfo.allUser ?? [];
    if (MahjongContext().getPlayback) {
      menuIndex = 2;
    } else if (MahjongContext.roomInfo.gameInfo.status == 5) {
      menuIndex = 1;
    }
    selectUser = allUser[0];
    initUserCard();
    super.initState();
  }

  void initUserCard() {
    userCards = [];
    if (selectUser?.win ?? false) {
      userCards
          .add(CardWidget.buildBottomCard(selectUser!.winCard, cardHeight));
      userCards.add(SizedBox(
        width: cardHeight / 2,
      ));
    }
    var index = 0;
    selectUser?.getUserHandCards().forEach((e) {
      // 如果是自摸的话  这里需要移出一张手牌
      if (e == selectUser!.winCard &&
          index == 0 &&
          selectUser!.getUserHandCards().length % 3 == 2) {
        index++;
      } else {
        userCards.add(CardWidget.buildBottomCard(e, cardHeight));
      }
    });
    userCards.add(SizedBox(
      width: cardHeight / 2,
    ));

    /**
     * @type 1 碰牌,2 暗杠, 3 明杠 , 4 点杠
     */
    selectUser?.openDeal?.forEach((e) {
      if (e.type == 1) {
        userCards.add(CardWidget.buildExportCardInfo(e.card, cardHeight));
        userCards.add(CardWidget.buildExportCardInfo(e.card, cardHeight));
        userCards.add(CardWidget.buildExportCardInfo(e.card, cardHeight));
      } else if (e.type == 2) {
        userCards.add(CardWidget.buildExportCardInfo(null, cardHeight));
        userCards.add(
            CardWidget.buildSuperpositionCard(e.card, cardHeight, dark: true));
        userCards.add(CardWidget.buildExportCardInfo(null, cardHeight));
      } else {
        userCards.add(CardWidget.buildExportCardInfo(e.card, cardHeight));
        userCards.add(
            CardWidget.buildSuperpositionCard(e.card, cardHeight, dark: false));
        userCards.add(CardWidget.buildExportCardInfo(e.card, cardHeight));
      }

      userCards.add(SizedBox(
        width: cardHeight / 2,
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: Colors.transparent,
        child: Center(
            child: AnimatedOpacity(
          opacity: _opacity,
          duration: const Duration(seconds: 1),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.r),
            child: Container(
              width: dialogWidth,
              height: ScreenUtil().screenHeight * 0.7,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  // 顶部当前用户开始
                  Container(
                    height: 50.h,
                    width: dialogWidth,
                    padding: EdgeInsets.only(left: 20.w, right: 20.w),
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color.fromARGB(255, 249, 206, 172),
                          Color.fromARGB(255, 160, 160, 160)
                        ],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.0, 1.0],
                        tileMode: TileMode.clamp,
                      ),
                    ),
                    child: Flex(
                      direction: Axis.horizontal,
                      children: [
                        Expanded(
                            flex: 1,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                MahjongCommon.headerImage(
                                    selectUser!.portraitUrl,
                                    height: 40.h,
                                    width: 40.h),
                                SizedBox(
                                  width: 20.w,
                                ),
                                Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      selectUser?.username ?? "",
                                      style: TextStyle(
                                          color: const Color.fromARGB(
                                              255, 126, 26, 1),
                                          fontSize: 15.h,
                                          fontWeight: FontWeight.bold),
                                    ),
                                    Text(
                                      "ID:${selectUser!.userId}",
                                      style: TextStyle(
                                          color: const Color.fromARGB(
                                              255, 126, 26, 1),
                                          fontSize: 10.h,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ],
                                )
                              ],
                            )),
                        Expanded(
                            flex: 1,
                            child: Text(
                              selectUser?.fractions
                                      ?.fold(
                                          0,
                                          (value, element) =>
                                              value + element.fraction)
                                      .toString() ??
                                  "0",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Color.fromARGB(255, 126, 26, 1),
                                  fontSize: 20.h,
                                  fontWeight: FontWeight.bold),
                            )),
                        Expanded(
                            flex: 1,
                            child: Text(
                              selectUser!.win ? "WIN" : "",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color:
                                      const Color.fromARGB(255, 253, 253, 253),
                                  shadows: AppContent.colors
                                      .map((color) => Shadow(
                                            color: color,
                                            offset: Offset(2.0, 2.0),
                                            blurRadius: 5.0,
                                          ))
                                      .toList(),
                                  fontSize: 20.h,
                                  fontWeight: FontWeight.bold),
                            )),
                      ],
                    ),
                  ),
                  // 中间部分  卡牌 积分开始.........
                  Expanded(
                    flex: 3,
                    child: Container(
                        color: Color.fromARGB(255, 255, 251, 208),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Container(
                              width: double.infinity,
                              height: cardHeight *
                                  (2 - MahjongContext().exportDiagonalRatio),
                              padding: EdgeInsets.only(left: cardHeight / 2),
                              child: SingleChildScrollView(
                                scrollDirection: Axis.horizontal,
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: userCards,
                                ),
                              ),
                            ),
                            Expanded(
                                child: SingleChildScrollView(
                              child: Table(
                                //border: TableBorder.all(),
                                children: selectUser?.fractions
                                        ?.map((e) => TableRow(
                                              children: [
                                                TableCell(
                                                  child: Center(
                                                      child: Text(
                                                    e.targetUserName,
                                                    style: TextStyle(
                                                        color: const Color
                                                            .fromARGB(
                                                            255, 126, 26, 1),
                                                        fontSize: 12.h,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  )),
                                                ),
                                                TableCell(
                                                  child: Text(
                                                    e.fractionInfo ?? "",
                                                    style: TextStyle(
                                                        color: const Color
                                                            .fromARGB(
                                                            255, 126, 26, 1),
                                                        fontSize: 12.h,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                    overflow: TextOverflow
                                                        .ellipsis, // 当文本溢出时使用省略号显示
                                                    maxLines: 1, // 最多显示一行
                                                  ),
                                                ),
                                                TableCell(
                                                  child: Center(
                                                      child: Text(
                                                    e.fraction.toString(),
                                                    style: TextStyle(
                                                        color: const Color
                                                            .fromARGB(
                                                            255, 126, 26, 1),
                                                        fontSize: 12.h,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  )),
                                                ),
                                              ],
                                            ))
                                        .toList() ??
                                    [],
                              ),
                            )),
                            // -------------- 其它用户开始------------
                            SizedBox(
                              height: 50.h,
                              child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: MahjongContext
                                          .roomInfo.gameInfo.allUser
                                          ?.map((user) => GestureDetector(
                                                child: Container(
                                                  height: 40.h,
                                                  width: 120.w,
                                                  margin: EdgeInsets.only(
                                                      left: 20.h),
                                                  decoration: BoxDecoration(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            5),
                                                    gradient:
                                                        const LinearGradient(
                                                      colors: [
                                                        Color.fromARGB(
                                                            255, 172, 199, 248),
                                                        Color.fromARGB(
                                                            255, 233, 247, 252)
                                                      ],
                                                      begin:
                                                          Alignment.topCenter,
                                                      end: Alignment
                                                          .bottomCenter,
                                                      stops: [0.0, 1.0],
                                                      tileMode: TileMode.clamp,
                                                    ),
                                                  ),
                                                  child: Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceAround,
                                                    children: [
                                                      MahjongCommon.headerImage(
                                                          user.portraitUrl,
                                                          height: 30.h,
                                                          width: 30.h),
                                                      Column(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .spaceAround,
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: [
                                                          Text(
                                                            user.username ?? "",
                                                            style: TextStyle(
                                                                color: const Color
                                                                    .fromARGB(
                                                                    255,
                                                                    126,
                                                                    26,
                                                                    1),
                                                                fontSize: 13.h,
                                                                height: 1.0,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold),
                                                          ),
                                                          Text(
                                                            user.fractions
                                                                    ?.fold(
                                                                        0,
                                                                        (value, element) =>
                                                                            value +
                                                                            element.fraction)
                                                                    .toString() ??
                                                                "0",
                                                            style: TextStyle(
                                                                color: const Color
                                                                    .fromARGB(
                                                                    255,
                                                                    126,
                                                                    26,
                                                                    1),
                                                                fontSize: 15.h,
                                                                height: 1.0,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold),
                                                          ),
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                ),
                                                onTap: () {
                                                  selectUser =
                                                      allUser.firstWhere(
                                                          (obj) =>
                                                              obj.userId ==
                                                              user.userId,
                                                          orElse: () =>
                                                              allUser[0]);
                                                  initUserCard();
                                                  setState(() {});
                                                },
                                              ))
                                          .toList() ??
                                      []),
                            )
                          ],
                        )),
                  ),
                  Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: [
                          Color.fromARGB(27, 255, 255, 255),
                          Color.fromARGB(110, 0, 0, 0),
                        ],
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        GestureDetector(
                          onTapDown: (details) {
                            setState(() {
                              _opacity = 0.0;
                            });
                          },
                          onTapUp: (details) {
                            setState(() {
                              _opacity = 1.0;
                            });
                          },
                          child: Text(
                            "长按查看桌面",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.sp,
                                fontFamily: "hyqmd"),
                          ),
                        ),
                        SizedBox(
                          width: 20.w,
                        ),
                        ElevatedButton(
                          onPressed: () {
                            menuList![menuIndex].fun();
                          },
                          style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.orange,
                              shadowColor: Colors.green),
                          child: Text(
                            menuList![menuIndex].name,
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.sp,
                                fontFamily: "hyqmd"),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        )));
  }
}
